package com.xhg.mqtt.templet;

import com.xhg.mqtt.constant.MqttConstants;
import com.xhg.mqtt.core.MqttSimpleClient;
import com.xhg.mqtt.dto.EventCodeEnum;
import com.xhg.mqtt.dto.MqttMessagePb;
import com.xhg.mqtt.listener.MessageEvent;
import com.xhg.mqtt.listener.MessageListener;
import com.xhg.mqtt.util.CommonUtil;
import com.xhg.mqtt.util.LogUtil;
import com.xhg.mqtt.util.ProtoBufUtil;
import java.util.Map;

public class MyListener implements MessageListener {

  @Override
  public void messageArrived(byte[] message) {
    try {
      //反序列化 具体业务处理
      MqttMessagePb.MqttMessage msg = ProtoBufUtil.decode(message);

      //解析头信息
      MqttMessagePb.MqttHead head = msg.getHead();
      //指令码
      String eventCode = head.getEventCode();
      //结果码
      int resultCode = head.getResultCode();
      //结果描述
      String resultDesc = head.getResultDesc();
      //消息id
      String messageId = head.getMessageId();
        //消息id
        int ack = head.getCc();

      //这里做具体的业务
      switch (EventCodeEnum.enumOf(eventCode)) {
        case BOX_INFO:
          LogUtil.print(EventCodeEnum.BOX_INFO.getDesc());
          break;
        case SITE_INFO:
          LogUtil.print(EventCodeEnum.SITE_INFO.getDesc());
          break;
        case VERSION_INFO:
          LogUtil.print(EventCodeEnum.VERSION_INFO.getDesc());
          break;
        case SERVER_NOTIFY:
          LogUtil.print(EventCodeEnum.SERVER_NOTIFY.getDesc());
          break;
        case DEVICE_LOGIN:
          LogUtil.print(EventCodeEnum.DEVICE_LOGIN.getDesc());
          break;
        case DEVICE_LOGOUT:
          LogUtil.print(EventCodeEnum.DEVICE_LOGOUT.getDesc());
          break;
        case DEVICE_WILL:
          LogUtil.print(EventCodeEnum.DEVICE_WILL.getDesc());
          break;
        default:
          break;
      }
      if (CommonUtil.isAck(ack)) {
          MqttSimpleClient.getInstance()
              .ackMessage(EventCodeEnum.DEVICE_LOGIN, messageId, "clientId", "1.0",MqttConstants.QOS);
      }
    } catch (Exception e) {
      LogUtil.print("处理消息异常");
      e.printStackTrace();
    }
  }

  @Override
  public String failMessage(Map<String, MessageEvent> failMsgMap) {
    System.out.println("有失败消息" + failMsgMap.keySet().toString());
    //入库保存失败消息
    for (String key : failMsgMap.keySet()) {
      System.out.println(key);
      return key;
    }
//        return failMsgMap.keySet().toString().replace("[","").replace("]","");
    return null;
  }


  @Override
  public void connectComplete(boolean isConnect)  {
    System.out.println("初始化连接:"+isConnect+"--------"+MqttSimpleClient.getInstance());
  }

  @Override
  public void reconnect(boolean isConnect)  {
    System.out.println("是否重连:"+isConnect);
  }
}
